package com.fuhao.route;

import com.fuhao.utils.RabbitUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhang
 */
public class consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitUtils.getConnection();

        final Channel channel = connection.createChannel();

        //每一个消费者都需要创建对列，每个消费者队列名不一致
        channel.queueDeclare("exchange_direct_queue1",true,false,false,null);
        //把队列绑定到路由器中,第一个参数：队列名，第二个参数：路由器名  第三个参数 路由键，direct需要绑定路由键
        channel.queueBind("exchange_direct_queue1","exchange_direct","add");

        //后面的接收逻辑与工作队列模型一致
        //公平分发的话需要保证每次只接收一条消息
        channel.basicQos(1);//保证一次只分发一个
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"UTF-8");
                System.out.println("direct类型消费者1接收消息 "+ msg );
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            }
        };
        channel.basicConsume("exchange_direct_queue1",false,consumer);
    }
}
